package com.clz.hyperit.controller;

import java.util.Map;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.clz.hyperit.entity.User;
import com.clz.hyperit.entity.UserDetail;
import com.clz.hyperit.exception.ApplicationRunTimeException;
import com.clz.hyperit.service.UserDetailService;
import com.clz.hyperit.service.UserService;
import com.clz.hyperit.util.Email;
import com.clz.hyperit.util.MD5Util;
import com.clz.hyperit.util.MapUtil;
import com.clz.hyperit.util.RandomCode;
import com.clz.hyperit.util.ResultMessage;
import com.clz.hyperit.util.VerifyCodeImage;
import com.clz.hyperit.vo.OcassionMail;
import com.clz.hyperit.util.SendEmail;


@RestController
@RequestMapping(value = "/user")
public class UserController {
	@Autowired
	private UserService userService;
	
	@Autowired
	private UserDetailService userDetailService;
	
	@Autowired
	private MapUtil mapUtil;
	
	private ResultMessage result = null;
	private final Logger logger = LoggerFactory.getLogger(UserController.class);

	/**
	 * 邮箱注册->发送邮件
	 * 
	 * @return
	 * @throws MessagingException
	 */
	@RequestMapping(value = "/sendEmail", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> SendEmail(HttpServletRequest request,
			String account, String password, String verifyCode)
			throws MessagingException {
		result = new ResultMessage();
		String text = (String) request.getSession().getAttribute("VerifyCode");
		if (userService.findByAccount(account) != null) {
			result.setServiceResult(false);
			result.setResultInfo("该邮箱已注册");
		} else if (text != null && text.equalsIgnoreCase(verifyCode)) {
			String code = RandomCode.randomChar();
			OcassionMail om  = new OcassionMail();
			om.setEmail(account);
			om.setPassword(password);
			om.setCode(code);
//			request.getSession().setAttribute("email", email);
//			request.getSession().setAttribute("password", password);
//			request.getSession().setAttribute("code", code);
			mapUtil.put(account,om);	        
			SendEmail.send(account, code,
					 request.getLocalAddr() + ":"+request.getLocalPort());
			result.setResultInfo("发送成功");
		} else {
			result.setResultInfo("验证码输入错误！");
		}
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	/**
	 * 激活注册
	 */
	@RequestMapping(value = "/activeRegister", method = RequestMethod.GET)
	public ModelAndView activeRegister(
			HttpServletRequest request, String lastemail, String lastcode) {
		ModelAndView modelAndView = new ModelAndView("/user/success"); 
		result = new ResultMessage();
//		String email = (String) request.getSession().getAttribute("email");
//		String password = (String) request.getSession().getAttribute("password");
//		String code = (String) request.getSession().getAttribute("code");
		OcassionMail ocassionmail=(OcassionMail)(mapUtil.getMap()).get(lastemail);
		if (ocassionmail.getCode() != null && ocassionmail.getEmail() != null && ocassionmail.getCode().equalsIgnoreCase(lastcode)
				&& ocassionmail.getEmail().equalsIgnoreCase(lastemail)) {
			User user = new User();
			String password = MD5Util.md5(ocassionmail.getPassword());
			user.setAccount(lastemail);
			user.setPassword(password);
			user.setRole_id(0);
			user.setStatus(1);
			Integer user_id = userService.saveRegister(user);
			userService.saveUserDetail(user_id);
			result.setResultInfo("注册成功");
		} else {
			result.setResultInfo("链接已过期");
		}
		mapUtil.remove(ocassionmail.getEmail());
		 modelAndView.addObject("ResultInfo", result); 
		 return modelAndView;
	}

	/**
	 * 用户登录
	 * 
	 * @param request
	 * @param account
	 * @param password
	 * @param verifyCode
	 * @param role
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> login(HttpServletRequest request,
			String account, String password, String verifyCode) {
		result = new ResultMessage();
		String text = (String) request.getSession().getAttribute("VerifyCode");
		if (text != null && !text.equalsIgnoreCase(verifyCode)) {
			throw new ApplicationRunTimeException("验证码错误");
		}
		User user = userService.findByAccount(account);
		if (user == null) {
			throw new ApplicationRunTimeException("没有该用户");
		}
		String password_md5 = MD5Util.md5(password);
		if (!password_md5.equals(user.getPassword())) {
			throw new ApplicationRunTimeException("密码错误");
		}
		if(user.getStatus()!=0){
			UserDetail userdetail = userService.getUserDetailByUserID(user.getId());
			// 将用户详情存放在session中.
			request.getSession().setAttribute("account", account);
			request.getSession().setAttribute("password", password);
			request.getSession().setAttribute("userDetail_id", userdetail.getId());
			result.setResultInfo("登录成功");
			result.getResultParm().put("userdetail", userdetail);
		}
		else{
			result.setResultInfo("该帐号已被封停");
		}
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}

	/**
	 * 获取图片验证码.
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getImgVerifyCode", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> getQRCode(HttpServletRequest request) {
		result = new ResultMessage();
		VerifyCodeImage v = new VerifyCodeImage();
		String path = v.getVerifyCode(request);
		request.getSession().setAttribute("VerifyCode", v.getText());
		System.out.println("图片验证码:" + v.getText());
		result.setServiceResult(true);
		result.setResultInfo("生成图片验证码成功");
		result.getResultParm().put("path", path);
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	/**
	 * 检测该帐号是否已经被注册
	 */
	@RequestMapping(value = "/isRegister", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> isRegister(String account) {
		result = new ResultMessage();
		boolean flag;
		logger.debug("检测帐号是否存在");
		if (userService.findByAccount(account) != null) {
			result.setResultInfo("该邮箱已注册");
			flag = false;
		}
		else {
				result.setResultInfo("该邮箱可用");flag = true;
			}
		result.getResultParm().put("flag", flag);
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	/**
	 * 修改密码
	 */
	@RequestMapping(value = "/updatePwd", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> updatePwd(Integer id,String password,String new_password){
		result = new ResultMessage();
//		UserDetail ud = userDetailService.getUserInfo(id);
			User user = userService.getById(id);
			if(MD5Util.md5(password).equals(user.getPassword())){
				user.setPassword(MD5Util.md5(new_password));
				userService.updatePwd(user);
				result.setServiceResult(true);
				result.setResultInfo("修改密码成功");
			}
			else{
				result.setResultInfo("原密码错误");
				result.setServiceResult(false);
			}
			return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	} 
	/**
	 * 找回密码1 发送邮件验证码
	 */
	@RequestMapping(value = "/stepone", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> stepone(HttpServletRequest request,
			String email, String verifyCode)
			throws MessagingException {
		result = new ResultMessage();
		String text = (String) request.getSession().getAttribute("VerifyCode");
		User user = userService.findByAccount(email);
		if(user==null){
			throw new ApplicationRunTimeException("邮箱不正确");
		}
		if (text != null && text.equalsIgnoreCase(verifyCode)) {
			String code = RandomCode.randomChar();
			request.getSession().setAttribute("email", email);
			request.getSession().setAttribute("code", code);        
			Email.send(email, code);
			result.setResultInfo("发送成功");
		} else {
			result.setResultInfo("验证码输入错误！");
		}
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	/**
	 * 找回密码2 填写验证码
	 */
	@RequestMapping(value = "/steptwo", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> steptwo(HttpServletRequest request,
			 String verifyCode,String newpassword)
			throws MessagingException {
		result = new ResultMessage();
		String text = (String) request.getSession().getAttribute("code");
		String email = (String )request.getSession().getAttribute("email");
		if (text != null && text.equalsIgnoreCase(verifyCode)) {  
			if(email==null){
				throw new ApplicationRunTimeException("验证码已过期");
			}
			String password_md5 = MD5Util.md5(newpassword);
			User user = userService.findByAccount(email);
			user.setPassword(password_md5);
			userService.updatePwd(user);		
			result.setResultInfo("修改成功");
		} else {
			result.setResultInfo("验证码输入错误！");
		}
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
	/**
	 * 普通注册
	 */
	@RequestMapping(value = "/common_regist", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<ResultMessage> common_regist(String account,String password){
		result = new ResultMessage();
		result.setServiceResult(true);
		if (userService.findByAccount(account) != null) {
			result.setServiceResult(false);
			result.setResultInfo("该邮箱已注册");
		}
		else{
			User user = new User();
			String password_md5 = MD5Util.md5(password);
			user.setAccount(account);
			user.setPassword(password_md5);
			user.setRole_id(0);
			user.setStatus(1);
			Integer user_id = userService.saveRegister(user);
			userService.saveUserDetail(user_id);
			result.setResultInfo("注册成功");
		}
		return new ResponseEntity<ResultMessage>(result, HttpStatus.OK);
	}
}
